import socket
from urllib import parse
from PyQt5.QtCore import QThread, pyqtSignal

# ip_port = ('172.20.10.14', 9999)
#
# s = socket.socket()
# s.connect(ip_port)
#
# s.sendall(bytes(parse.urlencode({"msg":"请求占领地球"}), encoding='utf-8'))
# print("已发送")
#
# server_reply = s.recv(1024*1024*5)
# print(parse.unquote(str(server_reply, encoding='utf-8')))
# s.close()


class Tcp(QThread):
    state_signal = pyqtSignal(str)
    recv_signal = pyqtSignal(str)
    send_signal = pyqtSignal(str)
    weather_signal = pyqtSignal(str, str, str)

    def __init__(self, ip, port, url):
        super(Tcp, self).__init__()
        self.ip = ip
        self.port = port
        self.ip_port = (self.ip, self.port)
        self.url = url
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print("tcp构造完成")

    def run(self):
        try:
            self.s.connect(self.ip_port)
            sendData = {
                "general": {
                    'method': 'GET / HTTP / 1.1',
                    'Host': self.ip + ":" + str(self.port)
                },
                "request": self.url
            }
            self.s.sendall(bytes(str(sendData), encoding='utf-8'))
            self.send_signal.emit(str(sendData))
            print(str(sendData), "已发送")

            response = self.s.recv(1024*1024*5)
            response = eval(str(response, encoding='utf-8'))

            msg = ''  # 存放所有要显示的信息
            # 头部信息
            header = response['header']
            for key, value in header.items():
                msg += "{}:{}\n".format(key, value)
            print("headermsg", msg)

            # 天气情况
            weather = eval(response['weather'])
            weatherState = weather['weather']  # 多云、晴天。。。
            high = weather['high']
            low = weather['low']
            self.weather_signal.emit(weatherState, high, low)

            # 新闻或其他
            string = '\n你好'
            if 'news' in response:
                string = '\n'
                news = eval(response['news'])
                print('news',type(news), news)
                for item in news:
                    string += "\t{}\n\t\t{}\n{}  \n\n".format(item['title'], item['pubTime'], item['content'])
                    string += ("-"*130 + "\n")

            msg += string
            self.recv_signal.emit(msg)
            print("接受", msg)
            self.s.close()
        except:
            self.state_signal.emit("连接失败，请检查ip+端口")

class Udp(QThread):

    state_signal = pyqtSignal(str)
    recv_signal = pyqtSignal(str)
    send_signal = pyqtSignal(str)
    weather_signal = pyqtSignal(str, str, str)

    def __init__(self, ip, port, url):
        super(Udp, self).__init__()
        self.ip = ip
        self.port = port
        self.ip_port = (self.ip, self.port)
        self.url = url
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    def run(self):
        try:
            sendData = {
                "general": {
                    'method': 'GET / HTTP / 1.1',
                    'Host': self.ip + ":" + str(self.port)
                },
                "request": self.url
            }
            data = str(sendData)
            self.send_signal.emit(data)
            self.s.sendto(bytes(data, encoding='utf-8'), self.ip_port)

            data, addr = self.s.recvfrom(1024*1024*5)
            response = eval(str(data, encoding='utf-8'))

            msg = ''  # 存放所有要显示的信息
            # 头部信息
            header = response['header']
            for key, value in header.items():
                msg += "{}:{}\n".format(key, value)
            print("headermsg", msg)

            # 天气情况
            weather = eval(response['weather'])
            weatherState = weather['weather']  # 多云、晴天。。。
            high = weather['high']
            low = weather['low']
            self.weather_signal.emit(weatherState, high, low)

            # 新闻或其他
            string = '\n你好'
            if 'news' in response:
                string = '\n'
                news = eval(response['news'])
                print('news', type(news), news)
                for item in news:
                    string += "\t{}\n\t\t{}\n{}  \n\n".format(item['title'], item['pubTime'], item['content'])
                    string += ("-" * 130 + "\n")

            msg += string
            self.recv_signal.emit(msg)
            print("接受", response)
            self.s.close()
        except Exception as e:
            print(str(e))
            self.state_signal.emit("连接失败，请检查ip+端口")



